<template>
  <div class="adjustmentProcess">
    <DFPageList ref="dfPageListRef" :pageOptions="pageOptions">
      <template #adjustmentBtn>
        <div class="ad-arr">
          <Draggable
            :list="adjustmentBtn"
            ghost-class="ghost"
            itemKey="id"
            :force-fallback="true"
            group="list"
            :fallback-class="true"
            :fallback-on-body="true"
            class="view-content"
          >
            <template #item="{ index }">
              <div>
                <n-tag
                  class="tags"
                  size="large"
                  :bordered="false"
                  closable
                  @close="handleClose(index)"
                >
                  <n-select
                    v-model:value="adjustmentBtn[index]"
                    filterable
                    :placeholder="$t('common.form.plSelect')"
                    :options="optionsListFn(adjustmentBtn[index])"
                    @update:value="handleUpdateValue"
                  />
                </n-tag>
              </div>
            </template>
          </Draggable>
        </div>
        <span class="addProcess" @click="addProcess"> + </span>
        <span class="subAddProcess">{{ t('adjustmentProcess.table.adjustmentBtinTips') }}</span>
      </template>
    </DFPageList>
  </div>
</template>

<script lang="ts" setup name="AdjustmentProcess">
  import lang from './lang';
  import { useMixins } from '@/hooks/useMixins';
  import {
    pageAdjustmentProcess,
    addAdjustmentProcess,
    updateAdjustmentProcess,
    delAdjustmentProcess,
  } from '@/api/gather/adjustmentProcess';
  import { listInterface } from '@/api/gather/interface';
  import { listInterfaceBtn } from '@/api/gather/interfaceBtn';
  import Draggable from 'vuedraggable';
  const { loadLangFn, t } = useMixins();
  loadLangFn(lang);

  const dfPageListRef: any = ref(null);

  const adjustmentBtn = ref([]);
  const optionsList = ref([]);

  const interfaceList = ref([]);

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'adjustmentProcessName',
        },
        {
          label: 'adjustmentProcessCode',
        },
      ],
    },
    table: {
      columns: [
        {
          width: 170,
          label: 'adjustmentProcessName',
        },
        {
          width: 170,
          label: 'adjustmentProcessCode',
        },
        {
          width: 170,
          label: 'remark',
          common: true,
        },
      ],
      action: {
        columns: [
          {
            label: 'edit',
          },
          {
            label: 'copy',
          },
          {
            label: 'delete',
          },
        ],
      },
      operaColumn: [
        {
          label: 'add',
        },
      ],
      requestFn: pageAdjustmentProcess,
      delRequestFn: delAdjustmentProcess,
    },
    modalFormDialog: {
      formSchemas: [
        {
          label: 'adjustmentProcessName',
          required: true,
          giProps: { span: 4 },
          span: 3,
        },
        {
          label: 'adjustmentProcessCode',
          required: true,
          giProps: { span: 4 },
          span: 3,
          editDialogDisabled: true,
        },
        {
          label: 'adjustmentBtn',
          slot: 'adjustmentBtn',

          giProps: { span: 4 },
          span: 3,
          rules: [
            {
              required: true,
              key: 'adjustmentBtn',
              validator(_rule, value: string) {
                if (!value || value.length === 0) {
                  return new Error(t('common.formTipMsg.input'));
                }
              },
              trigger: ['change'],
            },
          ],
        },
        {
          label: 'adjustmentInterface',
          required: true,
          giProps: { span: 4 },
          span: 3,
          component: 'NCheckbox',
          defaultValue: [],
          rules: [
            {
              type: 'array',
              required: true,
              message: t('common.formTipMsg.select'),
              trigger: ['change'],
            },
          ],

          componentProps: {
            options: computed(() => {
              if (interfaceList.value.length === 0) {
                return [
                  {
                    label: t('common.table.noData'),
                    value: t('common.table.noData'),
                    disabled: true,
                  },
                ];
              }

              return interfaceList.value.map((item) => ({
                label: item.interfaceName,
                value: item.interfaceCode,
              }));
            }),
          },
        },
        {
          label: 'remark',
          common: true,
          type: 'textarea',
          giProps: { span: 4 },
          span: 3,
        },
      ],
      cols: 2,
      addDataFn: addAdjustmentProcess,
      updateDataFn: updateAdjustmentProcess,
      afterDialogSubmitFn: initDictData,
      setDialogDataFn: async (data, type) => {
        if (type === 'add') {
          adjustmentBtn.value = [];
          const newData: any = {};
          return newData;
        }

        if (type === 'copy') {
          delete data.id;
        }

        if (data && data.adjustmentBtn) {
          adjustmentBtn.value = data.adjustmentBtn.split(',');
        }

        if (data && data.adjustmentInterface) {
          data.adjustmentInterface = data.adjustmentInterface.split(',');
        }

        return data;
      },
      setDialogSubmitDataFn: (data) => {
        data.adjustmentBtn = adjustmentBtn.value.join(',');

        data.adjustmentInterface = data.adjustmentInterface?.join(',') || null;
        return data;
      },
    },
  };

  async function initDictData() {
    const res = await Promise.all([listInterface(), listInterfaceBtn()]);
    const [list1, list2] = res;

    optionsList.value = list2.data.map((item) => ({
      ...item,
      label: item.btnName,
      value: item.btnCode,
    }));

    interfaceList.value = list1.data;
    // console.log('optionsList.value', optionsList.value);
  }

  initDictData();

  const addProcess = () => {
    adjustmentBtn.value.push('');
  };

  const handleClose = (index) => {
    adjustmentBtn.value.splice(index, 1);
  };

  const handleUpdateValue = (e) => {
    dfPageListRef.value.setFieldsValueFn({
      adjustmentBtn: adjustmentBtn.value.join(','),
    });
    if (e && e.length !== 0) {
      dfPageListRef.value?.validate(['adjustmentBtn']);
    }
  };

  const optionsListFn = (val) => {
    let valObj = optionsList.value.filter((item) => {
      return !adjustmentBtn.value.includes(item.value) || val === item.value;
    });

    return valObj;
  };
</script>

<style>
  .jsoneditor-poweredBy,
  .jsoneditor-transform,
  .jsoneditor-repair,
  .jsoneditor-sort {
    display: none;
  }
</style>

<style lang="less" scoped>
  .ad-arr {
    .n-select {
      margin-top: 8px;
      margin-bottom: 8px;
    }
    .tags {
      width: 100%;
      :deep(.n-tag__content) {
        flex: 1;
      }
    }
  }
  .addProcess {
    font-size: 26px;
    cursor: pointer;
  }
  .subAddProcess {
    font-size: 12px;
    color: #999;
    margin-left: 10px;
  }
</style>
